package com.mycompany.client;

import com.mycompany.protocol.RootJobCommand;
import com.mycompany.protocol.RootJobCommand.NestedJob;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *
 * @author Admin
 */
public class RootJobFrame extends JFrame {

    public RootJobFrame() {
        super("root job");
        JButton createButton = new JButton("CREATE");


        getContentPane().add(createButton, BorderLayout.EAST);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        setSize(300, 200);
    }

    public void updateRootJobPanel(RootJobCommand command) {
        JPanel rootJobPanel = new JPanel(new GridLayout(2, 0));
        rootJobPanel.add(getJobsPanel(command.getNestedJobs()));
        rootJobPanel.add(getUsersPanel(command.getUserNames()));
        getContentPane().add(rootJobPanel, BorderLayout.CENTER);
    }

    private JPanel getJobsPanel(List<NestedJob> nestedJobs) {
        JPanel jobsPanel = new JPanel(new GridLayout(0, 3));
        jobsPanel.add(new JLabel("Job name"));
        jobsPanel.add(new JLabel("Job creator"));
        jobsPanel.add(new JLabel("Job action"));
        for (int i = 0; i < nestedJobs.size(); i++) {
            NestedJob currentJob = nestedJobs.get(i);
            jobsPanel.add(new JLabel(currentJob.getJobName()));
            jobsPanel.add(new JLabel(currentJob.getCreatorName()));
            JButton joinButton = new JButton("join");
            joinButton.setActionCommand("button_" + i);
            joinButton.addActionListener(new JoinButtonListener());
            jobsPanel.add(joinButton);
        }

        return jobsPanel;
    }

    private JPanel getUsersPanel(List<String> users) {
        JPanel usersPanel = new JPanel(new GridLayout(0, 1));
        usersPanel.add(new JLabel("Connected users:"));
        for (String userName : users) {
            usersPanel.add(new JLabel(userName));
        }
        return usersPanel;
    }

    private static class JoinButtonListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("action source: " + e.getActionCommand());
        }
    }
//
//    public static void main(String[] args) {
//        List<NestedJob> nestedJobs = new ArrayList<NestedJob>();
//        nestedJobs.add(new NestedJob("name1", "creator1"));
//        nestedJobs.add(new NestedJob("name2", "creator2"));
//        RootJobFrame frame = new RootJobFrame();
//        RootJobCommand command = new RootJobCommand(nestedJobs, Arrays.asList("name1"));
//        frame.updateRootJobPanel(command);
//    }
}
